<?php

namespace App\Http\Controllers\Api\Goods;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\Models\Goods\Goods;
use App\Models\Goods\Order;
use App\Models\Members;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    private $order;

    public function __construct()
    {
        $this->order = new Context(new Order());
    }

    protected $orderStatus = [
        1 => "待发货",
        2 => "已发货",
        3 => "已完成"
    ];

    public function index(Request $request)
    {
        //获商品
        $goods = Goods::where('is_show',1)->get(['id','goods_name'])->map(function($item){
            $item->value = $item->id;
            $item->name = $item->goods_name;
            return $item;
        });
            $orders = $this->order->display(15,function($query) use($request){
                if($request->order_status)
                {
                    $query->where('order_status',$request->order_status);
                }
                if($request->order_keyword)
                {
                 $query->where('order_sn',$request->order_keyword)->orWhere('shop_code',$request->order_keyword);
                }
                if($request->receiving_name)
                {
                        $query -> where('consignee_name','like',"%{$request->receiving_name}%")->orWhere('consignee_mobile','like',"%{$request->receiving_name}%");
                }
                if(isset($request->create_time[0]) && !empty($request->create_time[0])){
                    $query->whereBetween('created_at',$request->create_time);
                }
                if($request->is_del)
                {
                    $query->where('deleted_at','<>',null);
                }
                return $query;
            });
          $orders->each(function($item){
                $item->order_status = $this->orderStatus[$item->order_status];
                $goods = Goods::where('id',$item->goods_id)->first();
                $item->goods_name = $goods['goods_name'];
                $users = Members::where('id',$item->user_id)->first();
                $item->member_name = $users->nickname;
            });
        return $orders;
    }

    public function show($id)
    {
        $order = $this->order->find($id);
        $member = $order->member;
        return $this->success([
            'order' => $order,
            'member' => $member
        ]);
    }

    public function destroy($id)
    {
        if(Order::destroy($id))
        {
            return $this->success(['message'=>'删除成功']);
        }
        return $this->error('删除失败');
    }
}
